<template>
  <BaseChatMsg :avatar="avatar" :align="align">
    <template v-slot:chatcontent>
      <div class="file">
        <div class="file-info">
          <div class="file-desc">
            <div class="file-name">{{ fileName }}</div>
            <div class="file-size">{{ getSize(size) }}</div>
          </div>
          <div class="file-icon">
            <svg-icon :icon="icon"></svg-icon>
          </div>
        </div>
        <div class="progress" v-if="loaded < 100">
          <van-progress :percentage="loaded" />
        </div>
      </div>
    </template>
  </BaseChatMsg>
</template>

<script>
import BaseChatMsg from './BaseChatMsg.vue'
export default {
  name: 'ChatMsgFile',
  components: { BaseChatMsg },
  props: {
    avatar: String,
    type: String,
    fileName: String,
    align: {
      type: String,
      validator: value => {
        return ['left', 'right'].includes(value)
      }
    },
    size: {
      type: [Number, String],
      validator: value => {
        return !isNaN(value)
      }
    },
    loaded: Number
  },
  computed: {
    icon() {
      const fileTypeMap = {
        image: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'wbmp', 'webp', 'tif', 'psd', 'svg'],
        text: ['txt', 'js', 'jsx', 'ts', 'tsx', 'json', 'css', 'less', 'scss', 'html', 'htm', 'xml'],
        tar: ['zip', 'gz', 'tgz', 'gzip', '7z', 'rar'],
        video: ['mp4', 'avi', 'wmv', 'mpeg'],
        audio: ['mp3', 'wav'],
        doc: ['doc', 'docx'],
        ppt: ['ppt', 'pptx'],
        xls: ['xls', 'xlsx'],
        pdf: ['pdf']
      }
      const ext = this.fileName.split('.').slice(-1)[0]
      let fileType = 'unknow'
      for (const type of Object.keys(fileTypeMap)) {
        if (fileTypeMap[type].includes(ext)) {
          fileType = type
          break
        }
      }
      return `file-${fileType}`
    }
  },
  methods: {
    getSize() {
      const size = Number(this.size)
      if (!size) return ''
      if (size < 1024) {
        return `${size} B`
      } else if (size < 1024 ** 2) {
        return `${(size / 1024).toFixed(2)} KB`
      } else if (size < 1024 ** 3) {
        return `${(size / 1024 ** 2).toFixed(2)} MB`
      } else {
        return `${(size / 1024 ** 3).toFixed(2)} GB`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.file {
  .file-info {
    display: flex;
    .file-desc {
      margin-right: 10px;
      flex: 1;
      .file-name {
        @include textoverflow(2);
        word-break: break-all;
      }
      .file-size {
        font-size: $font-size-sm;
        color: $gray-6;
      }
    }
    .file-icon {
      font-size: 50px;
    }
  }
  .progress {
    margin-top: 10px;
  }
}
</style>
